<template>
  <div class="w1200">
    <UserInfo />
    <DataStatistics />
    <div class="c-01">
      <div class="btn btn-01">{{ $t('最近5次登录') }}</div>
      <div class="btn btn-02" v-if="getUserInfo.apiKey" @click="copyToClipboard(getUserInfo.apiKey)">复制apiKey:{{
        getUserInfo.apiKey }}</div>
    </div>
    <div class="c-02">
      <el-table :data="tableData.slice(0, 5)" style="width: 100%"
        :header-row-style="{ 'background': '#f8f9fa', 'color': '#333' }">
        <el-table-column prop="createTime" :label="$t('登录时间')"
          :formatter="(row, colunm, val) => formatDateTime(new Date(val))">
        </el-table-column>
        <el-table-column prop="ip" label="IP">
        </el-table-column>
      </el-table>
    </div>
    <div class="c-03">
      <el-row :gutter="40">
        <el-col :span="6">
          <div class="title">
            <img src="@/assets/images/userinfo_icon_08.png" alt="">
            <span style="color: #2d62c8;">{{ $t('修改密码') }}</span>
          </div>
          <div class="cont">
            <el-form :model="form01" :rules="rulse01" ref="form01" size="mini">
              <el-form-item :label="$t('新密码')" prop="newPassword">
                <el-input v-model="form01.newPassword" type="password" :placeholder="$t('输入新密码')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('重复新密码')" prop="ensureNewPassword">
                <el-input v-model="form01.ensureNewPassword" type="password" :placeholder="$t('在输入一次')"></el-input>
              </el-form-item>
              <div class="btn" style="background: #2d62c8;" @click="submitPassword">{{ $t('确认修改密码') }}</div>
            </el-form>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="title">
            <img src="@/assets/images/userinfo_icon_03.png" alt="">
            <span style="color: #4ebe8b;">{{ $t('邮箱绑定') }}</span>
          </div>
          <div class="cont">
            <el-form :model="form02" :rules="rulse02" ref="form02" size="mini">
              <el-form-item :label="$t('安全邮箱')" prop="email">
                <el-input v-model="form02.email" type="text" :placeholder="$t('输入想要绑定的邮箱')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('验证码')" prop="code">
                <div style="display: flex;align-items: center;">
                  <el-input v-model="form02.code" type="text" :placeholder="$t('输入验证码')"></el-input>
                  <el-button type="primary" @click="sendCode" :disabled="code">发送</el-button>
                </div>
              </el-form-item>
              <div class="t1">
                {{ $t('已绑定第三方账号') }}: {{ $t('微信') }}
              </div>
              <div class="t1">{{ $t('如需解除第三方账号绑定，联系客服') }}</div>
              <div class="btn" style="background: #4ebe8b;" @click="submitEmail">{{ $t('提交更改') }}</div>
            </el-form>
          </div>

        </el-col>
        <el-col :span="6">
          <div class="title">
            <img src="@/assets/images/userinfo_icon_11.png" alt="">
            <span style="color: #3cc2e9;">{{ $t('邮件设置') }}</span>
          </div>
          <div class="cont">
            <el-form :model="form03" :rules="rulse03" ref="form03" size="mini">
              <el-form-item prop="psw">
                <el-checkbox v-model="form03.checked1" @change="pushEmail" :true-label="0" :false-label="1">{{
                  $t('订阅服务更新邮件') }}</el-checkbox>
                <el-checkbox v-model="form03.checked2" @change="pushCost" :true-label="0" :false-label="1">{{
                  $t('接受低余额提醒') }}</el-checkbox>
              </el-form-item>
              <el-form-item :label="$t('提醒金额')" prop="balanceReminderAmount">
                <el-input v-model="form03.balanceReminderAmount"></el-input>
              </el-form-item>
              <div class="btn" style="background: #3cc2e9;" @click="submitAmount">{{ $t('提交更改') }}</div>
            </el-form>
          </div>

        </el-col>
        <el-col :span="6">
          <div class="title">
            <img src="@/assets/images/userinfo_icon_05.png" alt="">
            <span style="color: #788ce0;">{{ $t('API设置') }}</span>
          </div>
          <div class="cont">
            <div class="t1">{{ $t('当前启用状态') }}</div>
            <div>
              <div class="t2">{{ $t('禁用') }}</div>
            </div>
            <div class="btn" style="background: #788ce0;">{{ $t('启用API功能') }}</div>
          </div>

        </el-col>
      </el-row>
    </div>
  </div>

</template>
<script>
import apiService from "@/api/apiService";
import UserInfo from "@/components/home/UserInfo.vue";
import DataStatistics from '@/components/home/DataStatistics.vue';
import { mapGetters } from "vuex";
import { formatDateTime } from '@/utils'


export default {
  data() {
    let validatePass = (rule, value, callback) => {
      const reg = /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])\S*$/
      if (!reg.test(value)) {
        callback(new Error(this.$t('包含大小写字母、数字')));
      } else {
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请再次输入密码')));
      } else if (value !== this.form01.newPassword) {
        callback(new Error(this.$t('两次输入密码不一致!')));
      } else {
        callback();
      }
    };
    return {
      formatDateTime,
      tableData: [
      ],

      form01: {
        newPassword: '',
        ensureNewPassword: ''
      },
      rulse01: {
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        ensureNewPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      form02: {
        email: '',
        code: '',
        userKey: '',
        mailKey: '',
      },
      rulse02: {
        email: [
          { required: true, message: this.$t('请输入邮箱地址'), trigger: 'blur' },
          { type: 'email', message: this.$t('请输入正确的邮箱地址'), trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, trigger: 'blur' }
        ]
      },
      form03: {
        balanceReminderAmount: '',
        checked1: '1',
        checked2: '1'
      },
      rulse03: {
        balanceReminderAmount: [
          { required: true, message: this.$t('请输入金额'), trigger: 'blur' },
        ],
      },
      code: false
    }
  },
  components: {
    UserInfo,
    DataStatistics
  },
  computed: {
    ...mapGetters(["getUserInfo"]),
  },
  mounted() {
    apiService.get('/loginLog').then(res => {
      this.tableData = res.data
    })
    this.$store.dispatch('getCurrentUserInfo').then(res => {
      const { email, isSubscribeCost, isSubscribeEmail, balanceReminderAmount } = res
      this.form02.email = email
      this.form03.checked1 = isSubscribeEmail
      this.form03.checked2 = isSubscribeCost
      this.form03.balanceReminderAmount = balanceReminderAmount
    })
  },
  methods: {
    // 修改密码
    submitPassword() {
      this.$refs.form01.validate(valid => {
        if (valid) {
          apiService.post("/modifyPassword", {
            ...this.form01
          }).then(() => {
            this.$message.success(this.$t('修改成功'))
          });
        }
      });
    },
    sendCode() {
      this.code = true
      this.$refs.form02.validateField(['email'], (error) => {
        if (error) {
          console.log("校验失败:", error);
        } else {
          apiService.post("/update-email", {
            ...this.form02
          }).then((res) => {
            this.$message.success(this.$t('发送成功'))
            this.form02.mailKey = res.data.mailKey
            this.form02.userKey = res.data.userKey
          });
        }

      });
    },
    // 修改邮件
    submitEmail() {
      this.$refs.form02.validate(valid => {
        if (valid) {
          apiService.post("/register/update-email", {
            ...this.form02
          }).then(() => {
            this.$message.success(this.$t('修改成功'))
          });
        }
      });
    },
    // 推送邮件
    pushEmail(val) {
      apiService.post("/push-email", {
        isSubscribeEmail: val
      }).then(() => {
        this.$message.success(this.$t('修改成功'))
      });
    },
    // 低余额推送
    pushCost(val) {
      apiService.post("/push-cost", {
        isSubscribeCost: val
      }).then(() => {
        this.$message.success(this.$t('修改成功'))
      });
    },
    //推送余额
    submitAmount() {
      this.$refs.form03.validate(valid => {
        if (valid) {
          apiService.post("/push-cost", {
            ...this.form03
          }).then(() => {
            this.$message.success(this.$t('修改成功'))
          });
        }
      });
    },
    copyToClipboard(text) {
      // const text = this.$refs.copy[index].textContent;
      // let text = this.$refs.copy[index].innerHTML;
      // text = text.replace(/<br>/g, '\n');
      // text = this.removeHTMLTags(text)
      const input = document.createElement('textarea');
      input.value = text; // 设置要复制的文本
      document.body.appendChild(input);
      input.select(); // 选中文本
      document.execCommand('copy'); // 执行复制操作
      document.body.removeChild(input); // 移除临时的输入框
      this.$message.success('内容已复制到剪贴板');
    },
  }
}
</script>
<style lang="scss" scoped>
.c-01 {
  display: flex;
  align-items: center;
  padding-top: 40px;

  .btn {
    height: 40px;
    padding: 0 20px;
    line-height: 40px;
    color: #fff;
    cursor: pointer;
    font-size: 16px;

    &.btn-01 {
      background-color: #5288e8;
    }

    &.btn-02 {
      background-color: #3dc3ea;
      margin-left: 20px;
    }
  }
}

.c-02 {
  padding-top: 10px;
}

.c-03 {
  padding-top: 40px;
  padding-bottom: 40px;

  .title {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;

    span {
      font-size: 14px;
      margin-left: 10px;
    }
  }

  .cont {
    border: 1px solid #ccc;
    padding: 20px;
    height: 240px;

    .t1 {
      font-size: 14px;
      color: #333;
      margin-bottom: 10px;
    }

    .t2 {
      height: 32px;
      display: inline-block;
      padding: 0 10px;
      line-height: 32px;
      color: #fff;
      font-size: 14px;
      background: #fe5858;
      margin-bottom: 10px;
    }

    .btn {
      height: 40px;
      padding: 0 10px;
      color: #fff;
      cursor: pointer;
      border-radius: 6px;
      display: inline-block;
      line-height: 40px;
      font-size: 14px;
    }

    ::v-deep .el-form-item {
      display: flex;
    }

    ::v-deep .el-form-item__label {
      flex-shrink: 0;
    }

    ::v-deep .el-form-item__content {
      width: 100%;
    }
  }
}
</style>